<?php
/**
 * This file is part of the wangningkai/olaindex.
 * (c) wangningkai <i@ningkai.wang>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Http\Controllers;

use App\Helpers\Tool;
use App\Http\Traits\ApiResponseTrait;
use App\Models\Account;
use App\Service\GraphErrorEnum;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use mysql_xdevapi\DatabaseObject;
use Validator;
use Cache;
use GuzzleHttp;

class ImageController extends BaseController
{
    use ApiResponseTrait;

    /**
     * 图床
     * @return mixed
     */
    public function index()
    {
        return view(setting('main_theme', 'default') . '.image');
    }

    /**
     * 图床上传图片
     * @param Request $request
     * @return JsonResponse
     */
    public function upload(Request $request)
    {
//        $socket_id = $request->get('socket_id', '');
//        if(!$socket_id){
//            return $this->fail('加载有问题，请重新刷新页面', 404);
//        }


        $accounts = Account::fetchlist();
        $account_id = 0;
        $hash = '';
        if ($accounts) {
            $account_id = setting('image_host_account');
            if (!$account_id) {
                $account_id = setting('primary_account', 0);
            }
            if (!$account_id) {
                $account_id = array_get($accounts->first(), 'id');
            }
            $account = $accounts->where('id', $account_id)->first();
            $hash = array_get($account, 'hash_id');
        }
        if (!$account_id) {
            return $this->fail('账号不存在', 404);
        }

        $account = Account::find($account_id);
        if (!$account) {
            return $this->fail('账号不存在', 404);
        }
        $config = $account->config;

        $field = 'olaindex_img';
        if (!$request->hasFile($field)) {
            return $this->fail('上传文件为空', 400);
        }
        $file = $request->file($field);
        $max_size = 1024 * 1024 * 10;//最大支持10G
        $rule = [$field => "required|max:{$max_size}|file"];
        $validator = Validator::make(
            request()->all(),
            $rule
        );
        if ($validator->fails()) {
            return $this->fail($validator->errors()->first(), 400);
        }
        if (!$file->isValid()) {
            return $this->fail('文件上传出错', 400);
        }
        $path = $file->getRealPath();
        if (file_exists($path) && is_readable($path)) {
//原来的方法
//            $content = file_get_contents($path);
//            $hostingPath = url_encode(array_get($config, 'image_path', '/'));
//            $middleName = '/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . str_random(8) . '/';
//            $filePath = trim($hostingPath . $middleName . $file->getClientOriginalName(), '/');
//            $root = array_get($config, 'root', '/');
//            $root = trim($root, '/');
//            $query = "{$root}/$filePath";
//            $service = $account->getOneDriveService();
//            $resp = $service->upload($query, $content);
//            if (array_key_exists('code', $resp)) {
//                $msg = array_get($resp, 'message', '文件上传出错');
//                $msg = GraphErrorEnum::get($resp['code']) ?? $msg;
//                return $this->fail($msg, 400);
//            }
//
//            $data = [
//                'item' => $resp,
//                'filename' => $resp['name'],
//                'size' => $resp['size'],
//                'time' => $resp['lastModifiedDateTime'],
//                'url' => shorten_url(route('drive.query', ['hash' => $hash, 'query' => url_encode($filePath), 'download' => 1])),
//            ];

            //超大文件上传

//            $hostingPath = url_encode(array_get($config, 'image_path', '/'));
//            $middleName = '/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . str_random(8) . '/';
//            $filePath = trim($hostingPath . $middleName . $file->getClientOriginalName(), '/');
//            $_path = dirname($filePath);//远程路径
//            $_file = basename($filePath);//远程文件名
//
//            $service = $account->getOneDriveService();
//            $resp = $service->createUploadSession($_path, $_file);
//            if(empty($resp['uploadUrl'])){
//                var_dump($resp);
//                die;
//            }
//            $uploadUrl = $resp['uploadUrl'];
//            $length = 20000000;//每次上传20M
//            $start = 0;
//            $filesize = _filesize($path);
//            $contentLength = $filesize > $length ? $length : $filesize;
//            $content = get_file_content($path, $start, $contentLength);
//            $end = $start+$contentLength-1;
//            //开始上传
//            $data = [];
//            $data = $service->resumableUpload($uploadUrl, $start, $end, $contentLength, $filesize, $content);
////            $http = new GuzzleHttp\Client;
////            $percent = ($end+1)/$filesize;
////            $http->get("http://1.15.100.180:9090/{$socket_id}/{$percent}");
//
//            while (empty($data['file'])){
//
//                $nextExpectedRanges = explode('-',$data['nextExpectedRanges'][0]);
//                $start_index= $nextExpectedRanges[0];
//                $end_index = $nextExpectedRanges[1];
//
//                $start = $nextExpectedRanges[0];
//                $contentLength = $start+$length-1 > $filesize-1 ? $end_index-$start_index+1 : $length;
//                $end = $start + $contentLength - 1;
//                $content = get_file_content($path, $start, $contentLength);
//
//                $data = $service->resumableUpload($uploadUrl, $start, $end, $contentLength, $filesize, $content);
////                $percent = ($end+1)/$filesize;
////                $http->get("http://1.15.100.180:9090/{$socket_id}/{$percent}");
//
//            }
//
////            echo "上传成功！\n";

//            Cache::flush();

//
//            $data = [
//                'item' => $data,
//                'filename' => $data['name'],
//                'size' => $data['size'],
//                'time' => $data['createdDateTime'],
//                'url' => shorten_url(route('drive.query', ['hash' => $hash, 'query' => url_encode($filePath), 'download' => 1])),
//            ];
//            @unlink($path);

            //异步任务处理
            $hostingPath = url_encode(array_get($config, 'image_path', '/'));
            $middleName = '/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . str_random(8) . '/';
            $filePath = trim($hostingPath . $middleName . 'tmp' . str_replace([' ','/'],'_',$file->getClientOriginalName()), '/');

            //把文件移动到其他地方
            $local_Path = base_path()."/".str_replace([' ','/'],'_',$filePath);//本地文件路径
            move_uploaded_file($path, $local_Path);

            $data = [
                'item' => 'file',
                'filename' => basename($filePath),
                'size' => _filesize($local_Path),
                'time' => date("Y-m-d H:i:s"),
                'url' => shorten_url(route('drive.query', ['hash' => $hash, 'query' => url_encode($filePath), 'download' => 1])),
            ];

            //向nodejs sockio发起异步任务
            $http = new GuzzleHttp\Client;
            $http->post("http://1.15.100.180:9090/upload",[
                'form_params' => [
                    'localPath' => $local_Path,
                    'remotePath' => $filePath,//远程文件路径
                    'account_id' => $account_id//存到哪个账户下面
                ]
            ]);

            return $this->success($data);
        }
        return $this->fail('无法获取文件内容', 400);
    }
}
